<template>
  <client-only>
    <div id="comments" class="comments-section">
      <div class="comments-header">
        <h3>评论</h3>
        <span class="comment-count">{{ commentCount || 0 }} 条评论</span>
      </div>

      <!-- 评论输入框 -->
      <div class="comment-input-area">
        <img :src="headerImg" alt="avatar" class="avatar" />
        <div class="input-container">
          <textarea
            v-model="newComment"
            placeholder="写下你的评论..."
            class="comment-textarea"
            @keydown.enter.exact.prevent="submitComment"
          ></textarea>
          <div class="input-actions">
            <button :disabled="!newComment.trim()" class="submit-button" @click="submitComment">
              发布评论
            </button>
          </div>
        </div>
      </div>

      <!-- 评论列表 -->
      <div v-if="comments.length > 0" class="comments-list">
        <div v-for="comment in comments" :key="comment.id" class="comment-item">
          <img :src="headerImg" alt="avatar" class="avatar" />
          <div class="comment-content">
            <div class="comment-author">
              <span class="author-name">{{ comment.username }}</span>
              <span class="comment-date">
                {{ formatTime(comment.createTime) }}
              </span>
            </div>
            <p class="comment-text">{{ comment.content }}</p>
            <div class="comment-actions">
              <button class="action-button" @click="likeComment(comment)">
                <i class="like-icon"></i>
                <span>{{ comment.likes || 0 }} 赞</span>
              </button>
              <button class="action-button" @click="toggleReplyInput(comment)">
                {{ getReplyStatus(comment.id) ? '取消回复' : '回复' }}
              </button>
              <!-- 删除按钮 - 仅当是自己的评论时显示 -->
              <button
                v-if="currentUserId && comment.userId === currentUserId"
                class="action-button delete-button"
                @click="confirmDelete(comment)"
              >
                删除
              </button>
            </div>

            <!-- 一级评论的回复输入框 -->
            <div v-show="getReplyStatus(comment.id)" class="reply-input-area">
              <div class="input-container">
                <textarea
                  :ref="(el: any) => setReplyInputRef(el, comment.id)"
                  v-model="replyComments[comment.id]"
                  :placeholder="`回复 ${comment.username}...`"
                  class="comment-textarea reply-textarea"
                  @keydown.enter.exact.prevent="() => submitReplyComment(comment)"
                ></textarea>
                <div class="input-actions">
                  <button
                    :disabled="!replyComments[comment.id]?.trim()"
                    class="submit-button"
                    @click="() => submitReplyComment(comment)"
                  >
                    发布回复
                  </button>
                </div>
              </div>
            </div>

            <!-- 二级回复列表 -->
            <div v-if="comment.replies && comment.replies.length > 0" class="replies-list">
              <div v-for="reply in comment.replies" :key="reply.id" class="reply-item">
                <div class="reply-content">
                  <div class="reply-author">
                    <span class="author-name">{{ reply.username }}</span>
                    <span v-if="reply.replyToUsername" class="reply-to">
                      回复 <span class="target-user">{{ reply.replyToUsername }}</span>
                    </span>
                    <span class="comment-date">
                      {{ formatTime(reply.createTime) }}
                    </span>
                  </div>
                  <p class="reply-text">{{ reply.content }}</p>
                  <div class="reply-actions">
                    <button class="action-button" @click="likeComment(reply)">
                      <i class="like-icon"></i>
                      <span>{{ reply.likes || 0 }} 赞</span>
                    </button>
                    <!-- 二级评论可以回复 -->
                    <button class="action-button" @click="toggleReplyInput(reply)">
                      {{ getReplyStatus(reply.id) ? '取消回复' : '回复' }}
                    </button>
                    <!-- 删除按钮 - 仅当是自己的评论时显示 -->
                    <button
                      v-if="currentUserId && reply.userId === currentUserId"
                      class="action-button delete-button"
                      @click="confirmDelete(reply)"
                    >
                      删除
                    </button>
                  </div>

                  <!-- 二级回复的回复输入框 -->
                  <div v-show="getReplyStatus(reply.id)" class="reply-input-area nested-reply">
                    <div class="input-container">
                      <textarea
                        :ref="(el: any) => setReplyInputRef(el, reply.id)"
                        v-model="replyComments[reply.id]"
                        :placeholder="`回复 ${reply.username}...`"
                        class="comment-textarea reply-textarea"
                        @keydown.enter.exact.prevent="() => submitReplyComment(reply)"
                      ></textarea>
                      <div class="input-actions">
                        <button
                          :disabled="!replyComments[reply.id]?.trim()"
                          class="submit-button"
                          @click="() => submitReplyComment(reply)"
                        >
                          发布回复
                        </button>
                      </div>
                    </div>
                  </div>

                  <!-- 三级回复列表 -->
                  <div
                    v-if="reply.replies && reply.replies.length > 0"
                    class="replies-list nested-replies"
                  >
                    <div
                      v-for="subReply in reply.replies"
                      :key="subReply.id"
                      class="reply-item nested-reply-item"
                    >
                      <div class="reply-content">
                        <div class="reply-author">
                          <span class="author-name">{{ subReply.username }}</span>
                          <span v-if="subReply.replyToUsername" class="reply-to">
                            回复 <span class="target-user">{{ subReply.replyToUsername }}</span>
                          </span>
                          <span class="comment-date">
                            {{ formatTime(subReply.createTime) }}
                          </span>
                        </div>
                        <p class="reply-text">{{ subReply.content }}</p>
                        <div class="reply-actions">
                          <button class="action-button" @click="likeComment(subReply)">
                            <i class="like-icon"></i>
                            <span>{{ subReply.likes || 0 }} 赞</span>
                          </button>
                          <!-- 删除按钮 - 仅当是自己的评论时显示 -->
                          <button
                            v-if="currentUserId && subReply.userId === currentUserId"
                            class="action-button delete-button"
                            @click="confirmDelete(subReply)"
                          >
                            删除
                          </button>
                          <!-- 三级评论不可回复，不显示回复按钮 -->
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <EmptyState v-else title="暂无评论" description="快来抢沙发吧！" />
    </div>
  </client-only>
</template>

<script setup lang="ts">
import { message, Modal } from 'ant-design-vue'
import { ref, defineProps, defineEmits, onMounted, nextTick } from 'vue'
import headerImg from '@/assets/image/header.png'
import dayjs from 'dayjs'
import { getCommonts, addCommont, deleteComment, getCommontCount } from '@/api/comment'
import storage from '@/utils/storage'
// 定义评论数据结构
interface Comment {
  id: number
  articleId: number
  userId: number
  username: string
  parentId: number | null
  replyToUserId: number | null
  replyToUsername: string | null
  content: string
  createTime: string
  replies: Comment[] | null
  likes?: number
}

const props = defineProps<{
  articleId: string
}>()

// 使用 props.articleId 来满足 eslint 规则
console.log('Article ID for comments:', props.articleId)

const emit = defineEmits<{
  (e: 'commentCount', value: number): void
}>()

// 评论相关数据
const newComment = ref('')
const comments = ref<Comment[]>([])
const replyComments = ref<Record<number, string>>({})
const replyInputsRef = ref<Record<number, HTMLTextAreaElement | null>>({})
const activeReplyIds = ref<number[]>([])
const commentCount = ref(0)

// 当前用户ID（在实际应用中应该从用户状态管理中获取）
// 这里为了演示，我们假设当前用户ID为2（与示例数据中的用户ID一致）
const currentUserId = ref<number>(storage.get('user')?.id) // 实际项目中应该从store或props获取

// 格式化时间
const formatTime = (time: string) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm')
}

// 设置回复输入框引用
const setReplyInputRef = (el: HTMLTextAreaElement | null, commentId: number) => {
  replyInputsRef.value[commentId] = el
}

const getList = () => {
  getCommonts(props.articleId).then((res: any) => {
    if (res.code === 200) {
      comments.value = res.data as Comment[]
    }
  })
  getCommontCount(props.articleId).then((res: any) => {
    if (res.code === 200) {
      commentCount.value = res.data
      emit('commentCount', res.data)
    }
  })
}

// 获取评论
onMounted(() => {
  getList()
})

// 提交评论
const submitComment = () => {
  // 拦截登录，如果未登录跳转到登录页面
  if (!currentUserId.value) {
    message.error('请先登录')
    navigateTo('/login' + '?redirect=' + encodeURIComponent(window.location.pathname))
    return
  }
  if (!newComment.value.trim()) return

  const comment: any = {
    articleId: props?.articleId,
    content: newComment.value,
    parentId: null,
    replyToUserId: null,
  }

  addCommont(comment).then((res: any) => {
    if (res.code === 200) {
      message.success('评论成功')
      newComment.value = ''
      getList()
    }
  })
}

// 点赞评论
const likeComment = (comment: Comment) => {
  // 这里应该调用点赞接口，暂时只更新本地状态
  comment.likes = (comment.likes || 0) + 1
}

// 切换回复输入框显示状态
const toggleReplyInput = (comment: Comment) => {
  const index = activeReplyIds.value.indexOf(comment.id)
  if (index >= 0) {
    // 如果已存在，则移除（隐藏）
    activeReplyIds.value.splice(index, 1)
    // 清空对应的回复内容（使用空字符串而不是删除属性）
    replyComments.value[comment.id] = ''
  } else {
    // 如果不存在，则添加（显示）
    activeReplyIds.value.push(comment.id)
    // 初始化回复内容为空
    replyComments.value[comment.id] = ''

    // 下一帧聚焦到输入框
    nextTick(() => {
      const input = replyInputsRef.value[comment.id]
      if (input) {
        input.focus()
      }
    })
  }
}

// 获取回复状态
const getReplyStatus = (commentId: number) => {
  return activeReplyIds.value.includes(commentId)
}

// 提交回复评论
const submitReplyComment = (comment: Comment) => {
  const replyContent = replyComments.value[comment.id]
  if (!replyContent?.trim()) return

  const replyData: any = {
    articleId: props?.articleId,
    content: replyContent,
    parentId: comment.id || null,
    replyToUserId: comment.userId || null,
  }

  addCommont(replyData).then((res: any) => {
    if (res.code === 200) {
      message.success('回复成功')
      // 清空回复内容
      replyComments.value[comment.id] = ''
      // 隐藏回复输入框
      const index = activeReplyIds.value.indexOf(comment.id)
      if (index >= 0) {
        activeReplyIds.value.splice(index, 1)
      }
      getList()
    }
  })
}

// 确认删除评论
const confirmDelete = (comment: Comment) => {
  Modal.confirm({
    title: '确认删除',
    content: '确定要删除这条评论吗？删除后无法恢复。',
    okText: '确认',
    cancelText: '取消',
    onOk: () => {
      deleteComment(String(comment.id))
        .then((res: any) => {
          if (res.code === 200) {
            message.success('删除成功')
            getList() // 重新获取评论列表
          } else {
            message.error('删除失败')
          }
        })
        .catch(() => {
          message.error('删除失败')
        })
    },
  })
}
</script>

<style scoped>
.comments-section {
  margin-top: 48px;
  padding-top: 24px;
  border-top: 2px solid #f7fafc;
}

.comments-header {
  margin-bottom: 24px;
}

.comments-header h3 {
  font-size: 20px;
  font-weight: 600;
  color: #1a202c;
  display: inline-block;
  margin: 0;
}

.comment-count {
  font-size: 14px;
  color: #718096;
  margin-left: 8px;
}

.comment-input-area {
  display: flex;
  gap: 12px;
  margin-bottom: 32px;
}

.comment-input-area .avatar {
  width: 40px;
  height: 40px;
  flex-shrink: 0;
  border-radius: 50%;
}

.input-container {
  flex: 1;
}

.comment-textarea {
  width: 100%;
  min-height: 100px;
  padding: 12px;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  font-size: 15px;
  line-height: 1.5;
  resize: vertical;
  transition: border-color 0.2s;
  font-family: inherit;
}

.reply-textarea {
  min-height: 60px;
}

.comment-textarea:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
}

.input-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 12px;
}

.submit-button {
  background: #667eea;
  color: white;
  border: none;
  border-radius: 6px;
  padding: 8px 16px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.2s;
}

.submit-button:hover:not(:disabled) {
  background: #5a6fd8;
}

.submit-button:disabled {
  background: #a0aec0;
  cursor: not-allowed;
}

.comments-list {
  margin-top: 24px;
}

.comment-item {
  display: flex;
  gap: 12px;
  padding: 16px 0;
  border-bottom: 1px solid #f7fafc;
}

.comment-item:last-child {
  border-bottom: none;
}

.comment-item .avatar {
  width: 40px;
  height: 40px;
  flex-shrink: 0;
  border-radius: 50%;
}

.comment-content {
  flex: 1;
}

.comment-author {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.author-name {
  font-size: 15px;
  font-weight: 600;
  color: #1a202c;
}

.comment-date {
  font-size: 13px;
  color: #a0aec0;
}

.comment-text {
  font-size: 15px;
  line-height: 1.6;
  color: #4a5568;
  margin: 0 0 12px 0;
}

.comment-actions,
.reply-actions {
  display: flex;
  gap: 16px;
}

.action-button {
  display: flex;
  align-items: center;
  gap: 4px;
  background: none;
  border: none;
  color: #718096;
  font-size: 14px;
  cursor: pointer;
  padding: 4px;
}

.action-button:hover {
  color: #667eea;
}

.delete-button {
  color: #e53e3e;
}

.delete-button:hover {
  color: #c53030;
}

.reply-input-area {
  margin-top: 16px;
  padding: 16px;
  background-color: #f8fafc;
  border-radius: 8px;
}

.reply-input-area.nested-reply {
  margin-top: 12px;
  padding: 12px;
  background-color: #edf2f7;
}

.replies-list {
  margin-top: 16px;
  padding-left: 20px;
  border-left: 2px solid #e2e8f0;
}

.replies-list.nested-replies {
  margin-top: 12px;
  padding-left: 15px;
  border-left: 1px dashed #cbd5e0;
}

.reply-item {
  padding: 12px 0;
  border-bottom: 1px dashed #e2e8f0;
}

.reply-item:last-child {
  border-bottom: none;
}

.reply-item.nested-reply-item {
  padding: 10px 0;
  border-bottom: 1px dotted #e2e8f0;
}

.reply-content {
  flex: 1;
}

.reply-author {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}

.reply-author .author-name {
  font-size: 14px;
  font-weight: 500;
}

.reply-to {
  font-size: 13px;
  color: #718096;
}

.reply-to .target-user {
  color: #667eea;
  font-weight: 500;
}

.reply-text {
  font-size: 14px;
  line-height: 1.5;
  color: #4a5568;
  margin: 0 0 8px 0;
}

.no-comments {
  text-align: center;
  padding: 40px 0;
  color: #a0aec0;
}

/* 移动端样式 */
@media (max-width: 968px) {
  .comment-input-area {
    flex-direction: column;
  }

  .comment-item {
    flex-direction: column;
  }
}
</style>
